package app;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Database {
	private String filename;
	private Connection connection = null;
	private Statement statement = null;
	
	public void connect() {
		try {
			connection = DriverManager.getConnection("jdbc:sqlite:" + filename);
			statement = connection.createStatement();
			statement.setQueryTimeout(30);
		} catch (SQLException e) {
			System.out.println(e.getMessage());
		}
	}
	
	public void disconnect() {
		try {
			connection.close();
		} catch (SQLException e) {
			System.out.println(e.getMessage());
		}
	}
	
	/**
	 * This method takes all tuples from given table and column.
	 * @param table Name of table.
	 * @param column Name of column.
	 * @return List with all data from chosen table and column.
	 */
	public List<Double> getTuples(String table, String column) {
		List<Double> tuples = new ArrayList<>();
		String sql = "SELECT " + column + " FROM " + table;
		
		try {
			ResultSet rs = statement.executeQuery(sql);
			while (rs.next()) {
				tuples.add(rs.getDouble(1));
			}
		} catch (SQLException e) {
			System.out.println(e.getMessage());
		}
		return tuples;
	}
	
	public List<Map<String, Double>> getAllTuples(String table) {
		List<Map<String, Double>> tuples = new ArrayList<>();
		List<String> columns = new ArrayList<>();
		
		String sql = "PRAGMA table_info('"+ table +"')";
		try {
			ResultSet rs = statement.executeQuery(sql);
			while (rs.next()) {
				//if (rs.getString(3).equals("INTEGER")) {
					//System.out.println(rs.getString(2));
					columns.add(rs.getString(2));
				//}
			}
			
			sql = "SELECT * FROM "+ table;
			rs = statement.executeQuery(sql);
			
			while (rs.next()) {
				Map<String, Double> tuple = new HashMap<>();
				for (String column : columns) {
					int columnIndex = rs.findColumn(column);
					tuple.put(column, rs.getDouble(columnIndex));
				}
				tuples.add(tuple);
			}
			
		} catch (SQLException e) {
			System.out.println(e.getMessage());
		}
		
		return tuples;
	}
	
	
	
	// Accessible methods
	public void setDatabaseFile(String filename) {
		this.filename = filename;
	}

}
